package ro.peoplecentric.ctc.faces.model;

import java.io.IOException;
import java.io.Serializable;
import javax.annotation.Resource;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ro.peoplecentric.ctc.faces.i18n.JsfMessagePublisher;

/**
 * Abstract model bean.
 *
 * @author pguzun
 */
public abstract class BaseModelBean implements Serializable {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private JsfMessagePublisher messagePublisher;

    /**
     * Get current {@link HttpServletRequest}
     *
     * @return request
     */
    public HttpServletRequest getRequest() {
        return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    }

    /**
     * Get current {@link HttpServletResponse}
     *
     * @return response
     */
    public HttpServletResponse getResponse() {
        return (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
    }

    /**
     * Redirect.
     *
     * @param url the url to redirect to.
     */
    public void redirect(String url) {
        try {
            ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
            context.redirect(context.getRequestContextPath() + url);
        } catch (IOException e) {
            // ok
        }
    }

    /**
     * Forward. NOTE: faces context is not available after dispatching.
     *
     * @param url the url to forward to.
     */
    public void forward(String url) {
        try {
            ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
            context.getSession(true);
            RequestDispatcher dispatcher = ((ServletRequest) context.getRequest()).getRequestDispatcher(url);
            dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse());
        } catch (IOException | ServletException ex) {
            // ok
        }
    }

    /**
     * @return the logger
     */
    public Logger getLogger() {
        return logger;
    }

    /**
     * @return the messagePublisher
     */
    public JsfMessagePublisher getMessagePublisher() {
        return messagePublisher;
    }
}
